package flower.home.common.poi;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.BuiltinFormats;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 使用xssf_sax_API处理Excel,请参考： http://poi.apache.org/spreadsheet/how-to.html#xssf_sax_api
 * <p/>
 * Also see Standard ECMA-376, 1st edition, part 4, pages 1928ff, at
 * http://www.ecma-international.org/publications/standards/Ecma-376.htm
 * <p/>
 * A web-friendly version is http://openiso.org/Ecma/376/Part4
 */
public class XSSFSheetHandler extends DefaultHandler {

    /**
     * Table with styles
     */
    private StylesTable stylesTable;

    /**
     * Table with unique strings
     */
    private ReadOnlySharedStringsTable sharedStringsTable;

    /**
     * Destination for data
     */
    private final PrintStream output;

    /**
     * Number of columns to read starting with leftmost
     */
    private final int minColumnCount;

    /**
     * Set when V start element is seen
     */
    private boolean vIsOpen;

    /**
     * Set when cell start element is seen;
     * used when cell close element is seen.
     */
    private XssfDataType nextDataType;

    /**
     * Used to format numeric cell values.
     */
    private short formatIndex;
    private String formatString;
    private final DataFormatter formatter;

    private int thisColumn = -1;

    /**
     * The last column printed to the output stream
     */
    private int lastColumnNumber = -1;

    /**
     * Gathers characters as they are seen.
     */
    private StringBuffer value;
    private String[] record;
    private List<String[]> rows = new ArrayList<>();
    private boolean isCellNull = false;

    /**
     * Accepts objects needed while parsing.
     *
     * @param styles  Table of styles
     * @param strings Table of shared strings
     * @param cols    Minimum number of columns to show
     * @param target  Sink for output
     */
    public XSSFSheetHandler(StylesTable styles,
                            ReadOnlySharedStringsTable strings, int cols, PrintStream target) {
        this.stylesTable = styles;
        this.sharedStringsTable = strings;
        this.minColumnCount = cols;
        this.output = target;
        this.value = new StringBuffer();
        this.nextDataType = XssfDataType.NUMBER;
        this.formatter = new DataFormatter();
        record = new String[this.minColumnCount];
        // 每次读取都清空行集合
        rows.clear();
    }

    /**
     * (non-Javadoc)
     *
     * @see DefaultHandler#startElement(String,
     * String, String, Attributes)
     */
    @Override
    public void startElement(String uri, String localName, String name, Attributes attributes) {

        if ("inlineStr".equals(name) || "v".equals(name)) {
            vIsOpen = true;
            // Clear contents cache
            value.setLength(0);
        } else if ("c".equals(name)) {
            // c => cell
            // Get the cell reference
            String r = attributes.getValue("r");
            int firstDigit = -1;
            for (int c = 0; c < r.length(); ++c) {
                if (Character.isDigit(r.charAt(c))) {
                    firstDigit = c;
                    break;
                }
            }
            thisColumn = nameToColumn(r.substring(0, firstDigit));
            // Set up defaults.
            this.nextDataType = XssfDataType.NUMBER;
            this.formatIndex = -1;
            this.formatString = null;
            String cellType = attributes.getValue("t");
            String cellStyleStr = attributes.getValue("s");
            if ("b".equals(cellType)) {
                nextDataType = XssfDataType.BOOL;
            } else if ("e".equals(cellType)) {
                nextDataType = XssfDataType.ERROR;
            } else if ("inlineStr".equals(cellType)) {
                nextDataType = XssfDataType.INLINESTR;
            } else if ("s".equals(cellType)) {
                nextDataType = XssfDataType.SSTINDEX;
            } else if ("str".equals(cellType)) {
                nextDataType = XssfDataType.FORMULA;
            } else if (cellStyleStr != null) {
                // It's a number, but almost certainly one
                // with a special style or format
                int styleIndex = Integer.parseInt(cellStyleStr);
                XSSFCellStyle style = stylesTable.getStyleAt(styleIndex);
                this.formatIndex = style.getDataFormat();
                this.formatString = style.getDataFormatString();
                if (this.formatString == null) {
                    this.formatString = BuiltinFormats.getBuiltinFormat(this.formatIndex);
                }
            }
        }
    }

    /**
     * (non-Javadoc)
     *
     * @see DefaultHandler#endElement(String,
     * String, String)
     */
    @Override
    public void endElement(String uri, String localName, String name) throws SAXException {
        String thisStr = null;
        // v => contents of a cell
        if ("v".equals(name)) {
            // Process the value contents as required.
            // Do now, as characters() may be called more than once
            switch (nextDataType) {
                case BOOL:
                    char first = value.charAt(0);
                    thisStr = first == '0' ? "FALSE" : "TRUE";
                    break;
                case ERROR:
                    thisStr = "\"ERROR:" + value.toString() + '"';
                    break;
                case FORMULA:
                    // A formula could result in a string value,
                    // so always add double-quote characters.
                    thisStr = '"' + value.toString() + '"';
                    break;
                case INLINESTR:
                    XSSFRichTextString rtsi = new XSSFRichTextString(
                            value.toString());
                    thisStr = '"' + rtsi.toString() + '"';
                    break;
                case SSTINDEX:
                    String sstIndex = value.toString();
                    try {
                        int idx = Integer.parseInt(sstIndex);
                        sharedStringsTable.skippedEntity("rPh");
                        XSSFRichTextString rtss = new XSSFRichTextString(
                                sharedStringsTable.getItems().get(idx));
                        thisStr = rtss.toString().trim().replaceAll("^\\s|\\s$", "");
                    } catch (NumberFormatException ex) {
                        output.println("Failed to parse SST index '" + sstIndex
                                + "': " + ex.toString());
                    }
                    break;
                case NUMBER:
                    String n = value.toString();
                    // 判断是否是日期格式
                    if (HSSFDateUtil.isADateFormat(this.formatIndex, n)) {
                        Double d = Double.parseDouble(n);
                        Date date = HSSFDateUtil.getJavaDate(d);
                        thisStr = formateDateToString(date);
                    } else if (this.formatString != null) {
                        thisStr = formatter.formatRawCellContents(
                                Double.parseDouble(n), this.formatIndex,
                                this.formatString);
                    } else {
                        try {
                            thisStr = formatter.formatRawCellContents(
                                    Double.parseDouble(n), 0, "General");
                        } catch (Exception e) {
                            thisStr = n;
                        }
                    }
                    break;

                default:
                    thisStr = "(TODO: Unexpected type: " + nextDataType + ")";
                    break;
            }
            // Output after we've seen the string contents
            // Emit commas for any fields that were missing on this row
            if (lastColumnNumber == -1) {
                lastColumnNumber = 0;
            }
            //判断单元格的值是否为空
            if (thisStr == null || isCellNull) {
                // 设置单元格是否为空值
                isCellNull = true;
            }
            if (thisColumn < minColumnCount) {
                record[thisColumn] = thisStr;
            }
            // Update column
            if (thisColumn > -1) {
                lastColumnNumber = thisColumn;
            }
        } else if ("row".equals(name)) {
            // Print out any missing commas if needed
            if (minColumnCount > 0) {
                // Columns are 0 based
                if (lastColumnNumber == -1) {
                    lastColumnNumber = 0;
                }
                if (!isCellNull && !checkBlankRow(record)) {
                    // 判断是否空行
                    rows.add(record.clone());
                    isCellNull = false;
                    for (int i = 0; i < record.length; i++) {
                        record[i] = "";
                    }
                }
            }
            lastColumnNumber = -1;
        }
    }

    private boolean checkBlankRow(String[] cellArr) {
        if(cellArr == null){
            return true;
        }
        for (String cell : cellArr) {
            if(cell != null && !"".equals(cell.trim())){
                return false;
            }
        }
        return true;
    }

    /**
     * 空格替换
     * @param str
     * @return
     */
   /* private String replaceBlank(String str) {
        String dest = "";
        if (str!=null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }*/

    public List<String[]> getRows() {
        return rows;
    }

    /**
     * Captures characters only if a suitable element is open. Originally
     * was just "v"; extended for inlineStr also.
     */
    @Override
    public void characters(char[] ch, int start, int length) {
        if (vIsOpen) {
            value.append(ch, start, length);
        }
    }

    /**
     * Converts an Excel column name like "C" to a zero-based index.
     *
     * @param name
     * @return Index corresponding to the specified name
     */
    private int nameToColumn(String name) {
        int column = -1;
        for (int i = 0; i < name.length(); ++i) {
            int c = name.charAt(i);
            column = (column + 1) * 26 + c - 'A';
        }
        return column;
    }

    private String formateDateToString(Date date) {
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);

    }

}
